<template>
    <div id="mainDiv">
        <div id="tools">
            <el-button id="initBtn" @click="initdata">初始化数据</el-button>
            <el-button id="pointBtn" @click="load_intresting_point">加载兴趣点</el-button>
            <el-button id="lineBtn" @click="loadtrackline(null,false)">加载地理轨迹线</el-button>
            <el-button id="polyBtn"  @click="loadtracked(null,true)">添加可以播放的轨迹</el-button>
            <el-button id="clearBtn" @click="clear">清除所有轨迹线</el-button>
        </div>

        <div id="cesiumContainer">
            <!-- <CesiumViewer v-if="viewer" :viewer="viewer"></CesiumViewer> -->
        </div>

        <div id="credit"></div>
    </div>
</template>
<script>
 
    //import buildModuleUrl from 'cesium/Cesium/'
    import Cesium from 'cesium/Cesium'
    import widgets from 'cesium/Widgets/widgets.css'
    import { clearInterval } from 'timers';
    // import CesiumViewer from '@/components/CesiumViewer'
 
export default {
    name: 'MainViewer',
    // components:{CesiumViewer},
    data () {
        return {
            viewer1:'viewer1',
            data1: {
                "type": "FeatureCollection",
                "features": [
                    {"geometry":{"coordinates":[[121.35243098,31.1270514],[121.35246032,31.12695799],
                    [121.35257289,31.12694875],[121.35268541,31.12696955],[121.35279327,31.12701599],
                    [121.35288455,31.12707645],[121.35298037,31.12711989],[121.35308069,31.12717385],
                    [121.35311073,31.12726482],[121.35305631,31.12735162],[121.35297873,31.1274306],
                    [121.35300829,31.12752041],[121.35303864,31.12761293],[121.35298113,31.12769198],
                    [121.35291825,31.12777645],[121.35285121,31.12784664],[121.35275248,31.12791279],
                    [121.35266306,31.12799179]],
                    "type":"LineString"},
                    "properties":
                    {
                        "植物数量":1.0,
                        "调查日期":"2019-04-02 10:38:27",
                        "植物名称":"啥啥啥",
                        "是否红色名录":false
                    },
                    "type":"Feature"
                    }
                ]
            },
            intrestingdata:[],
            trackline:[],
            tracklinegeojson: { 
                "type": "FeatureCollection",
                "features": []
            }

        }
    },
    mounted:function(){
        // this.viewer = new Cesium.Viewer('cesiumContainer',{
        //     animation: false,
        //     baseLayerPicker: false,
        //     fullscreenButton: false,
        //     geocoder: false,
        //     homeButton: false,
        //     sceneModePicker: false,
        //     selectionIndicator: false,
        //     timeline: false,
        //     navigationHelpButton: false,
        //     infoBox: false,
        //     navigationInstructionsInitiallyVisible: false
        // });
        // this.viewer._cesiumWidget._creditContainer.style.display = "none";  //去掉logo

        // 设置静态资源目录
        // Cesium.Core.buildModuleUrl.setBaseUrl('../../static/Cesium/');
        // 创建viewer实例
        var gmapstatellite = new Cesium.WebMapTileServiceImageryProvider({
            url : 'http://www.google.cn/maps/vt?lyrs=s@189&gl=cn&x={TileCol}&y={TileRow}&z={TileMatrix}',
            layer : 'USGSShadedReliefOnly',
            style : 'default',
            format : 'image/jpeg',
            tileMatrixSetID : 'gmapstatellite',
            // tileMatrixLabels : ['default028mm:0', 'default028mm:1', 'default028mm:2' ...],
            maximumLevel: 19,
            credit : new Cesium.Credit('U. S. Geological Survey')
        });
        var gmapstatellite_anntation = new Cesium.WebMapTileServiceImageryProvider({
            url : 'http://www.google.cn/maps/vt?lyrs=h@189&gl=cn&x={TileCol}&y={TileRow}&z={TileMatrix}',
            layer : 'USGSShadedReliefOnly',
            style : 'default',
            format : 'image/jpeg',
            tileMatrixSetID : 'gmapstatellite_anntation',
            // tileMatrixLabels : ['default028mm:0', 'default028mm:1', 'default028mm:2' ...],
            maximumLevel: 19,
            credit : new Cesium.Credit('U. S. Geological Survey')
        });
        var viewer = new Cesium.Viewer('cesiumContainer', {
            homeButton:false,
            baseLayerPicker:false,
            // timeline:false,
            // animation:false,
            creditContainer:"credit",
            targetFrameRate:10,
            requestRenderMode:true,
            selectionIndicator:false,
            // terrainProvider : new Cesium.CesiumTerrainProvider({
            //     url : "http://localhost/cdemo/tiles",
            //     requestVertexNormals : true
            // }),
            imageryProvider:gmapstatellite
        });
        var scene = viewer.scene;
        viewer.imageryLayers.addImageryProvider(gmapstatellite_anntation);
        viewer._cesiumWidget._creditContainer.style.display="none";
        //初始化数据
        // this.initdata();

        // viewer.camera.flyTo({
        //     destination:Cesium.Cartesian3.fromDegrees(114.0, 22.5)
        // })

        //Set the random number seed for consistent results.
    //   Cesium.Math.setRandomNumberSeed(3);

      //Set bounds of our simulation time
      

    //   var entityPosition = new Cesium.Cartesian3();
    //   var entityOrientation = new Cesium.Quaternion();
    //   var rotationMatrix = new Cesium.Matrix3();
    //   var modelMatrix = new Cesium.Matrix4();
    //   function computeModelMatrix(entity, time) {
    //       var position = Cesium.Property.getValueOrUndefined(entity.position, time, entityPosition);
    //       if (!Cesium.defined(position)) {
    //           return undefined;
    //       }
    //       var orientation = Cesium.Property.getValueOrUndefined(entity.orientation, time, entityOrientation);
    //       if (!Cesium.defined(orientation)) {
    //           modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position, undefined, modelMatrix);
    //       } else {
    //           modelMatrix = Cesium.Matrix4.fromRotationTranslation(Cesium.Matrix3.fromQuaternion(orientation, rotationMatrix), position, modelMatrix);
    //       }
    //       return modelMatrix;
    //   }

    //   var emitterModelMatrix = new Cesium.Matrix4();
    //   var translation = new Cesium.Cartesian3();
    //   var rotation = new Cesium.Quaternion();
    //   var hpr = new Cesium.HeadingPitchRoll();
    //   var trs = new Cesium.TranslationRotationScale();
    //   function computeEmitterModelMatrix() {
    //       hpr = Cesium.HeadingPitchRoll.fromDegrees(viewModel.heading, viewModel.pitch, viewModel.roll, hpr);

    //       trs.translation = Cesium.Cartesian3.fromElements(viewModel.transX, viewModel.transY, viewModel.transZ, translation);
    //       trs.rotation = Cesium.Quaternion.fromHeadingPitchRoll(hpr, rotation);

    //       return Cesium.Matrix4.fromTranslationRotationScale(trs, emitterModelMatrix);
    //   }

    //   //计算运动轨迹函数：时间+位置
    //   function computeCirclularFlight(lon, lat, radius) {
    //       var property = new Cesium.SampledPositionProperty();
    //       for (var i = 0; i <= 360; i += 45) {
    //           var radians = Cesium.Math.toRadians(i);
    //           var time = Cesium.JulianDate.addSeconds(start, i, new Cesium.JulianDate());//时间递增
    //           var position = Cesium.Cartesian3.fromDegrees(lon + (radius * 1.5 * Math.cos(radians)), lat + (radius * Math.sin(radians)),
    //               Cesium.Math.nextRandomNumber() * 500 + 1750);//位置变化
    //           property.addSample(time, position);
    //       }
    //       return property;
    //   }
     
      //计算模型随时间变化的位置
      //var circularPosition = computeCirclularFlight(-112.110693, 36.0994841, 0.03);
    //   var staticPosition = Cesium.Cartesian3.fromDegrees(114.110693, 22.5);//静止的位置

    //   var entity = viewer.entities.add({

    //       //Set the entity availability to the same interval as the simulation time.
    //       availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
    //           start: start,
    //           stop: stop
    //       })]),

    //       //Load the Cesium plane model to represent the entity
    //       model: {
    //         //   uri: '../Apps/SampleData/models/CesiumAir/Cesium_Air.gltf',
    //           uri: '../Apps/SampleData/plane.gltf',
    //           color: getColor('red', 1),
    //           minimumPixelSize: 54,//控制模型最小
    //           maximumScale:5//控制模型最大
    //       },

    //       position: staticPosition,
          
    //       //实时轨迹显示
    //       path: {
    //           show: true,
    //           leadTime: 0,//飞机将要经过的路径，路径存在的时间
    //           trailTime: 60,//飞机已经经过的路径，路径存在的时间
    //           width: 10,//线宽度
    //           resolution: 10,
    //           material: new Cesium.PolylineGlowMaterialProperty({
    //               glowPower: 0.3,//应该是轨迹线的发光强度
    //               color: Cesium.Color.PALEGOLDENROD//颜色
    //           })
    //       }
    //   });
    //   var entity = Box
    //   viewer.trackedEntity = entity;
    //   function getColor(colorName, alpha) {
    //       var color = Cesium.Color[colorName.toUpperCase()];
    //       return Cesium.Color.fromAlpha(color, parseFloat(alpha));
    //   }
      //根据geojson获取飞行路径
     
        //   var lineArray = jsonData.features[0].geometry.coordinates;

          this.mapviewer =viewer;

          this.mapviewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
                var pickedFeature = viewer.scene.pick(movement.position);
                console.log(pickedFeature)
                // if (typeof (pickedFeature) != "undefined")   //鼠标是否点到线上
                // {
                //     var name_id = pickedFeature.id.nameID;  //获取每条线的nameID
                //     Hightlightline(name_id);
                //     console.log(name_id);
                //     //TODO:触发选中的事件
                // }
                // else
                // {
                //     //如果没有选中任何线把高亮的线都去掉
                //     Highlight(currentHight,10, 10);
                // }
         }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        //  this.loadtracked();

    },
    methods:{
        initdata:function(starttime){
        

            console.log('初始化数据....')
            //由属性和点坐标+时间组成
            
            var trackline ={
                property:{
                    P1:'111111',
                    P2:'222222'
                },
                pointarray:[]
            }
            var startx = 114
            var starty = 22.5
           

            //创建兴趣点
            for (var i=0;i<50;i++)
            {
                //每隔5个创建一个兴趣点
                if(i%6==0)
                {
                    //每个兴趣点的属性不同
                    this.intrestingdata.push({lon:startx+i*0.1,lat:starty+i*0.1,property:{
                        Name:'111111_'+i,
                        P2:'222222_'+i
                    }})
                }
                
                trackline.pointarray.push(
                    [startx+i*0.1,starty+i*0.1]
                )   
            }


            this.tracklinegeojson.features.push(
            {
                "geometry": {
                    "coordinates": trackline.pointarray,
                    "type": "LineString"},
                    "properties": {
                            "UserID": 0,
                            "time": 3.0
                    },
                    "type": "Feature"
            });


            this.trackline.push(trackline);

            //trackline2
            //创建兴趣点
            var trackline2 ={
                property:{
                    P1:'111111',
                    P2:'222222'
                },
                pointarray:[]
            }
            
            for (var i=0;i<50;i++)
            {
                //每隔5个创建一个兴趣点

                if(i%6==0)
                {
                    //每个兴趣点的属性不同
                    this.intrestingdata.push({lon:startx,lat:starty+i*0.1,property:{
                        Name:'qqqq111111_'+i,
                        P2:'qqqq222222_'+i
                    }})
                }
                
                trackline2.pointarray.push(
                    [startx,starty+i*0.1]
                )   
            }
            
            this.tracklinegeojson.features.push(
            {
                "geometry": {
                    "coordinates": trackline2.pointarray,
                    "type": "LineString"},
                    "properties": {
                            "UserID": 0,
                            "time": 3.0
                    },
                    "type": "Feature"
            });

            this.trackline.push(trackline2);
            
        },

        load_intresting_point:function(geojosndata,entity_Array,flayto){
            //TODO:创建10个兴趣点
            var that = this
            var pinBuilder = new Cesium.PinBuilder();
           

                // var intrestedPoint = this.mapviewer.entities.add({
                //     name : name,
                //     position: Cesium.Cartesian3.fromDegrees(this.intrestingdata[i].lon, this.intrestingdata[i].lat),
                //     billboard : {
                //         image : pinBuilder.fromText('杨子锐', Cesium.Color.RED, 70).toDataURL(),
                //         verticalOrigin : Cesium.VerticalOrigin.BOTTOM
                //     }
                // });

                // var url = Cesium.buildModuleUrl('static/img/smallvip.png');
                // var groceryPin = Cesium.when(pinBuilder.fromUrl(url, Cesium.Color.GREEN, 60), function(canvas) {
                //     var g = canvas.toDataURL()
                //     for(var i=0;i<that.intrestingdata.length;i++)
                //     {
                //         var name = that.intrestingdata[i].property.Name;
                //         var position = Cesium.Cartesian3.fromDegrees(that.intrestingdata[i].lon, that.intrestingdata[i].lat);
                //         that.mapviewer.entities.add({
                //             name : name,
                //             position : position,
                //             billboard : {
                //                 image : g,
                //                 color: Cesium.Color.GREEN,
                //                 verticalOrigin : Cesium.VerticalOrigin.BOTTOM
                //             }
                //         });
                //     }
                // });

                var cameralPin = Cesium.when(pinBuilder.fromMakiIconId('camera', Cesium.Color.GREEN, 48), function(canvas) {
                    var g = canvas.toDataURL()
                    for(var i=0;i<that.intrestingdata.length;i++)
                    {
                        var name = that.intrestingdata[i].property.Name;
                        var position = Cesium.Cartesian3.fromDegrees(that.intrestingdata[i].lon, that.intrestingdata[i].lat);
                        that.mapviewer.entities.add({
                            name : name,
                            position : position,
                            billboard : {
                                image : canvas.toDataURL(),
                                verticalOrigin : Cesium.VerticalOrigin.BOTTOM
                            }
                        });
                    }
                });
            
        },

        loadtracked:function(dataarry,flayto){
            //创建一个对象
            //为对象添加trackline
            var pinBuilder = new Cesium.PinBuilder();
            for(var tc=0;tc<this.trackline.length;tc++)
            {
                // var Box = this.mapviewer.entities.add({
                //     name : 'box11111111111',
                //     //中心的位置（长、宽、高）
                //     position: Cesium.Cartesian3.fromDegrees(114.0, 22.5),
                //     box : {
                //         //长宽高
                //         dimensions : new Cesium.Cartesian3(4000.0, 3000.0, 2000.0),
                //         material : Cesium.Color.RED.withAlpha(0.5),
                //         fill : true,  //不显示填充
                //         outline : true, //显示轮廓
                //         outlineColor : Cesium.Color.BLACK
                //     },
                //     model: {
                //         //   uri: '../Apps/SampleData/models/CesiumAir/Cesium_Air.gltf',
                //         uri: '../Apps/SampleData/plane.gltf',
                //         color: getColor('red', 1),
                //         minimumPixelSize: 54,//控制模型最小
                //         maximumScale:5//控制模型最大
                //     },
                //     path: {
                //         show: true,
                //         leadTime: 0,//飞机将要经过的路径，路径存在的时间
                //         trailTime: 43200,//飞机已经经过的路径，路径存在的时间
                //         width: 10,//线宽度
                //         resolution: 10,
                //         material: new Cesium.PolylineGlowMaterialProperty({
                //             glowPower: 0.3,//应该是轨迹线的发光强度
                //             color: Cesium.Color.PALEGOLDENROD//颜色
                //         })
                //     }
                // });

                

                var tracker = this.mapviewer.entities.add({
                    name : 'Blank blue pin',
                    position: Cesium.Cartesian3.fromDegrees(114.0, 22.5),
                    billboard : {
                        image : pinBuilder.fromText('杨子锐', Cesium.Color.RED, 70).toDataURL(),
                        verticalOrigin : Cesium.VerticalOrigin.BOTTOM
                    },
                    path: {
                        show: true,
                        leadTime: 0,//飞机将要经过的路径，路径存在的时间
                        trailTime: 43200,//飞机已经经过的路径，路径存在的时间
                        width: 10,//线宽度
                        resolution: 10,
                        material: new Cesium.PolylineGlowMaterialProperty({
                            glowPower: 0.3,//应该是轨迹线的发光强度
                            color: Cesium.Color.PALEGOLDENROD//颜色
                        })
                    }
                });

                // var questionPin = viewer.entities.add({
                //     name : 'Question mark',
                //     position : Cesium.Cartesian3.fromDegrees(-75.1698529, 39.9220071),
                //     billboard : {
                //         image : pinBuilder.fromText('?', Cesium.Color.BLACK, 48).toDataURL(),
                //         verticalOrigin : Cesium.VerticalOrigin.BOTTOM
                //     }
                // });

                var lineArray =this.trackline[tc].pointarray


                var i=0
                var start = Cesium.JulianDate.fromDate(new Date(2017, 2, 25, 16));
                var stop = Cesium.JulianDate.addSeconds(start, 3600, new Cesium.JulianDate());

                //Make sure viewer is at the desired time.
                this.mapviewer.clock.startTime = start.clone();
                this.mapviewer.clock.stopTime = stop.clone();
                this.mapviewer.clock.currentTime = start.clone();
                this.mapviewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; //在时间结束后再次从开始重复
                this.mapviewer.clock.multiplier = 5;//时间流速

                //Set timeline to simulation bounds
                this.mapviewer.timeline.zoomTo(start, stop);//底部时间条控件调整

                var viewModel = {
                    rate: 5.0,
                    gravity: 0.0,
                    minimumLife: 1.0,
                    maximumLife: 1.0,
                    minimumSpeed: 5.0,
                    maximumSpeed: 5.0,
                    startScale: 1.0,
                    endScale: 4.0,
                    particleSize: 20.0,
                    transX: 2.5,
                    transY: 4.0,
                    transZ: 1.0,
                    heading: 0.0,
                    pitch: 0.0,
                    roll: 0.0,
                    fly: true,
                    spin: true,
                    show: true
                };
                //矩形更换为下面的图标
                // function getColor(colorName, alpha) {
                //     var color = Cesium.Color[colorName.toUpperCase()];
                //     return Cesium.Color.fromAlpha(color, parseFloat(alpha));
                // }
                // var staticPosition = Cesium.Cartesian3.fromDegrees(114.110693, 22.5);//静止的位置
                // var entity = viewer.entities.add({

                //         //Set the entity availability to the same interval as the simulation time.
                //         availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
                //             start: start,
                //             stop: stop
                //         })]),

                //         //Load the Cesium plane model to represent the entity
                //         model: {
                //             //   uri: '../Apps/SampleData/models/CesiumAir/Cesium_Air.gltf',
                //             uri: '../Apps/SampleData/plane.gltf',
                //             color: getColor('red', 1),
                //             minimumPixelSize: 54,//控制模型最小
                //             maximumScale:5//控制模型最大
                //         },

                //         position: staticPosition,
                        
                //         //实时轨迹显示
                //         path: {
                //             show: true,
                //             leadTime: 0,//飞机将要经过的路径，路径存在的时间
                //             trailTime: 60,//飞机已经经过的路径，路径存在的时间
                //             width: 10,//线宽度
                //             resolution: 10,
                //             material: new Cesium.PolylineGlowMaterialProperty({
                //                 glowPower: 0.3,//应该是轨迹线的发光强度
                //                 color: Cesium.Color.PALEGOLDENROD//颜色
                //             })
                //         }
                // });

                var entity = tracker

                var positions_arrary=[]

                var property = new Cesium.SampledPositionProperty();
                for (var i = 0;  i< lineArray.length; i ++) {
                    var lon = lineArray[i][0];
                    var lat = lineArray[i][1];
                    var dtime = 100*i;
                    var time = Cesium.JulianDate.addSeconds(start, dtime, new Cesium.JulianDate());//时间递增
                    var position = Cesium.Cartesian3.fromDegrees(lon, lat);//位置变化
                    positions_arrary.push(position)
                    property.addSample(time, position);
                }
                entity.position = property;
                entity.orientation = new Cesium.VelocityOrientationProperty(property);

                if(flayto){
                    this.mapviewer.flyTo(entity);
                }
            }

        },
        
        loadtrackline:function(entity_Array,flayto){
            var geojosndata = this.tracklinegeojson;
            //加载json数据，组织成Geojson格式
            //
            if(entity_Array==null)
                entity_Array = []
            var that = this
            var promise = Cesium.GeoJsonDataSource.load(geojosndata);  //显示管线数据  直接加载json数据 比把json转化成czml在加载 快很多
            promise.then(function (dataSource) {
                that.mapviewer.dataSources.add(dataSource);
                var entities = dataSource.entities.values;
                var colorHash = {};

                for (var o = 0; o < entities.length; o++) {
                    var r = entities[o];
                    console.log(r);
                    r.nameID = o;   //给每条线添加一个编号，方便之后对线修改样式
                    r.polyline.width = 10;  //添加默认样式
                    (r.polyline.material = new Cesium.PolylineGlowMaterialProperty({
                        glowPower: .1, //一个数字属性，指定发光强度，占总线宽的百分比。
                        color: Cesium.Color.ORANGERED.withAlpha(.9)
                    }), 10)
                
                }
                // var temp = new Array();
                window.currentHight = null;
                window.Hightlightline = function (nameid) {
                    if(nameid!=currentHight)//如果当前亮的不是自己
                    {
                        Highlight(nameid,50, 50);
                        currentHight = nameid;
                    }
                }
                window.Hightlightline_old = function (nameid) {
                    var exists = entity_Array.indexOf(nameid);
                    if (exists <= -1) {
                        Highlight(nameid,50, 50);
                        temp.push(nameid);  // 添加线nameID到数组，
                    }
                    else  //已经是高亮状态了 再次点击修改为原始状态
                    {
                        Highlight(nameid,10, 10);
                        temp.splice(exists, 1);  //删除对应的nameID
                    }
                }
                window.Highlight = function (nameid,width1, width2) {
                    for (var o = 0; o < entities.length; o++) {
                        var m = entities[o];
                        if (nameid == o) {
                            m.polyline.width = width1;
                            (m.polyline.material = new Cesium.PolylineGlowMaterialProperty({
                                glowPower: .1, //一个数字属性，指定发光强度，占总线宽的百分比。
                                color: Cesium.Color.ORANGERED.withAlpha(.9)
                            }), width2)
                        }
                    }
                }
            });
            if(flayto){
                this.mapviewer.flyTo(promise);
            }
            this.mapviewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
                var pickedFeature = that.mapviewer.scene.pick(movement.position);
                console.log(pickedFeature)
                if (typeof (pickedFeature) != "undefined")   //鼠标是否点到线上
                {
                    var name_id = pickedFeature.id.nameID;  //获取每条线的nameID
                    Hightlightline(name_id);
                    console.log(name_id);
                    //TODO:触发选中的事件
                }
                else
                {
                    //如果没有选中任何线把高亮的线都去掉
                    Highlight(currentHight,10, 10);
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        },
        clear:function(){
            this.mapviewer.entities.removeAll();
            this.mapviewer.dataSources.removeAll();
        }
    }
}
</script>
<style scoped>
    #mainDiv{
        width:100%;
        height:100%;
    }

    #cesiumContainer {
            position: absolute;
            /* top: 40px; */
            left: 0;
            height: 100%;
            width: 100%;
            margin: 0;
            overflow: hidden;
            padding: 0;
            font-family: sans-serif;
        }
        #tools {
            position: absolute;
            top: 0px;
            left: 0;
            display: inline;
            margin: 10px;
            padding: 0px;
            background: white;
            z-index: 1;
        }
        #logging {
            position: absolute;
            bottom: 0px;
            right: 0;
            display: inline;
            margin: 10px;
            padding: 10px;
            background: white;
        }
      html, body, #cesiumContainer {
          width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;
      }
</style>
